import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'

//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'

//注释掉mock.js
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'

//引入elementUI
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//配置Axios的全局属性和基础路径
import axios from "axios";
Vue.prototype.$http=axios;
//每次发送axios请求之前都会加上这个基础路径
axios.defaults.baseURL="http://localhost:8080";
//操.....defaults


//==axios的【前置拦截器】拦截调用后端的请求====================//
axios.interceptors.request.use(res=>{
  let token = localStorage.getItem("token");
  //如果登陆了，并且没有过期
  if(token){
    //将token的值设置到请求头
    res.headers["token"] = token;
  }
  return res;
},error => {
  Promise.reject(error)
})
//======================axios的前置拦截器【拦截调用后端的请求】====================//

//===axios的【后置拦截器】处理后台登录拦截的结果====================//
axios.interceptors.response.use(res => {
  //后端响应的是没有登录的信息  =>双重校验，防止执行因为后端异常报错的false
  if (false === res.data.success && ("noLogin" === res.data.msg || "timeOut" === res.data.msg)) {
    //跳转登录页面会在发送login请求时删除本地浏览器数据
    // localStorage.removeItem("token");
    // localStorage.removeItem("logininfo");
    // localStorage.removeItem("permissions");
    // localStorage.removeItem("menus");
    //跳转登陆页面
    router.push({path: '/login'});
  }
  return res;
},error => {
  Promise.reject(error)
})
//======================axios的后置拦截器【处理后台登录拦截的结果】====================//

//NProgress.configure({ showSpinner: false });

//通过路由规则定义路由
const router = new VueRouter({
  //router：router
  routes//等价于上面那一句，根据同名原则匹配
})

//【路由拦截拦截器】:拦截不发送ajax请求的的资源；404，login，register
router.beforeEach((to, from, next) => {
  //如果访问的是登陆页面
  if (to.path == '/login' || to.path == '/register') {
    localStorage.removeItem("token");
    localStorage.removeItem("logininfo");
    // localStorage.removeItem("permissions");
    // localStorage.removeItem("menus");
    next();
  }else {//访问的不是登陆和注册页面；访问受限资源
    let logininfo = JSON.parse(localStorage.getItem("logininfo"));
    if(logininfo){//有登陆信息
      next();
    }else{//没有登陆信息
      next({path:'/login'})
    }
  }

})

/*router.beforeEach((to, from, next) => {
  //NProgress.start();
  if (to.path == '/login') {
    sessionStorage.removeItem('user');
  }
  let user = JSON.parse(sessionStorage.getItem('user'));
  if (!user && to.path != '/login') {
    next({ path: '/login' })
  } e lse {
    next()
  }
})*/

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')

